import random

from django.core.validators import RegexValidator
from django.shortcuts import render, HttpResponse
from Utils.Tencent.sms import send_sms_single
from django.conf import settings


# Create your views here.

def send_sms(request):
    """发送短信
        ?tpl=login -> 11111
        ?tpl=register -> 22222
    """
    tpl = request.GET.get('tpl')
    template_id = settings.TENCENT_SMS_TEMPLATE.get(tpl)  # 获取定义在settings短信模板字典的值
    print(template_id)
    if not template_id:
        return HttpResponse("短信模板不存在")
    code = random.randrange(1000, 9999)  # 随机生成4位数
    res = send_sms_single("18071720400", template_id, [code, ])
    print(res)
    if res['result'] == 0:
        return HttpResponse("成功")
    else:
        return HttpResponse(res['errmsg'])


# 注册
from django import forms
from app01 import models


class RegisterModelForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput(), label="输入密码")
    new_password = forms.CharField(widget=forms.PasswordInput(), label="确认密码")
    moblie_phone = forms.CharField(label="手机号", validators=[RegexValidator(r'^(1[3|4|5|6|7|8|9])/d{9}$', "手机号格式错误"), ])
    code = forms.CharField(label="验证码")

    class Meta:
        model = models.UserInfo
        fields = ["username", "email", "password", "new_password", "moblie_phone", "code"]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, filed in self.fields.items():  # 给每个文本框加个class和提示消息
            filed.widget.attrs['class'] = 'form-control'
            filed.widget.attrs['placeholder'] = '请输入%s' % (filed.label,)


def registered(request):
    form = RegisterModelForm()

    return render(request, "app01/registered.html", {"form": form})



def login(request):

    return render(request, "app01/login.html")